package com.xnxkj.wx.micro.mch.bean;

import lombok.Data;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.security.KeyStore;

/**
 * 小微商户配置
 */
@Data
public class WxMerchantConfig {
    private String mchId;
    private String key;
    private SSLContext sslContext;

    public WxMerchantConfig(String mchId, String key, String certificateFilePath) throws FileNotFoundException {
        this(mchId, key, new File(certificateFilePath));
    }

    @SuppressWarnings("WeakerAccess")
    public WxMerchantConfig(String mchId, String key, File certificateFile) throws FileNotFoundException {
        this(mchId, key, new FileInputStream(certificateFile));
    }

    public WxMerchantConfig(String mchId, String key, byte[] certificate) {
        this(mchId, key, new ByteArrayInputStream(certificate));
    }

    public WxMerchantConfig(String mchId, String key, InputStream certificateInputStream) {
        this.mchId = mchId;
        this.key = key;
        try{
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            char[] password = mchId.toCharArray();
            keystore.load(certificateInputStream, password);
            this.sslContext = SSLContexts.custom().loadKeyMaterial(keystore, password).build();
        }catch (Exception e){
            throw new RuntimeException("读取证书异常", e);
        }
    }

    public WxMerchantConfig(String mchId, String key, SSLContext sslContext) {
        this.mchId = mchId;
        this.key = key;
        this.sslContext = sslContext;
    }
}
